package com.changgou.order.consumer;

import com.alibaba.fastjson.JSON;
import com.changgou.order.dao.OrderMapper;
import com.changgou.order.pojo.Order;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by zhangyuhong
 * Date:2020/5/21
 */
@Component
@RabbitListener(queues = "queue.order")
//监听订单支付状态,这里通过rabbitMQ给获取,发送方在changgou-service-pay支付的微服务
public class OrderPayMessageListener {

    @Autowired
    private OrderMapper orderMapper;

    @RabbitHandler  //和@RabbitListener配合使用,用于监听到消息就处理
    public void handler(Message message, Channel channel, String msg ) {
        System.out.println(msg);
        //1.获取消息本身
        //2.将其转换成MAP对象
        Map<String, String> map = JSON.parseObject(msg, Map.class);
        if (map != null) {
            String out_trade_no = map.get("out_trade_no");//订单号
            //3.判断是否支付成功 如果成功 则 更新状态
            if ("SUCCESS".equalsIgnoreCase(map.get("return_code"))) {
                try {
                    //支付成功 需要更新支付时间 支付流水号 支付的状态
                    Order order = orderMapper.selectByPrimaryKey(out_trade_no);
                    if (order == null) {
                        //没有就移除队列里的内容,拒签,不重回队列
                        channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                        return;
                    }
                    order.setPayStatus("1");
                    String time_end = map.get("time_end");//支付时间
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                    Date date = null;

                    date = dateFormat.parse(time_end);

                    order.setPayTime(date);//设置支付时间 time_end
                    order.setTransactionId(map.get("transaction_id"));//支付流水号
                    orderMapper.updateByPrimaryKeySelective(order);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Order order = orderMapper.selectByPrimaryKey(out_trade_no);
                order.setIsDelete("1");//已经删除
                //如果是支付失败 删除订单
                orderMapper.updateByPrimaryKeySelective(order);//逻辑删除
            }
        }
    }
}
